"""Core authentication code."""

import ldap
from hcp.ldap_models import Person
from django.conf import settings

SESSION_KEY = '_hcp_auth_user_dn'
REDIRECT_FIELD_NAME = 'login_redirect'

def get_user(request):
    """Retrieve the user object from a request.

    :Return:
        Returns a `hcp.ldap_models.Person` instance or None if the user is
        not currently logged in.
    """
    try:
        user_dn = request.session[SESSION_KEY]
        user = Person.objects.get_dn(user_dn)
    except (KeyError, ldap.NO_SUCH_OBJECT):
        user = None
    return user

def authenticate(username, password):
    """Check login credentials.

    :Parameters:
        - `username`: The "uid" of the user.
        - `password`: User password.

    :Return:
        Returns a `hcp.ldap_models.Person` instance or None if the
        credentials are invalid.
    """
    username = username.strip()
    try:
        person = Person.objects.get(uid=username)
    except ldap.NO_SUCH_OBJECT:
        return None

    # XXX: Logging
    try:
        conn = ldap.ldapobject.SmartLDAPObject(settings.LDAP_URI, who=person.dn, cred=password)
    except ldap.INVALID_CREDENTIALS:
        return None
    else:
        conn.unbind_s()

    return person

def login(request, user):
    """Indicate a user has logged in."""
    if user is None:
        user = request.user
    if SESSION_KEY in request.session:
        if request.session[SESSION_KEY] != user.dn:
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.dn
    if hasattr(request, 'user'):
        request.user = user

def logout(request):
    """Log out user from session db."""
    request.session.flush()
    if hasattr(request, 'user'):
        request.user = None


